package com.isyscore.os.metadata.utils;

import com.google.common.collect.Lists;
import com.isyscore.os.metadata.model.dto.SqlParseDTO;
import lombok.Data;
import org.apache.ibatis.parsing.GenericTokenParser;
import org.apache.ibatis.parsing.TokenHandler;

import java.util.List;
import java.util.Map;

public class MapVariablesParserUtils {
    public static SqlParseDTO parse(String string, Map<String,String> variables) {
        MapVariableTokenHandler handler = new MapVariableTokenHandler(variables);
        GenericTokenParser parser = new GenericTokenParser("#{", "}", handler);
        return SqlParseDTO.builder().sourceSql(string).parseSql(parser.parse(string)).sqlVariables(handler.getSqlVariables()).build();
    }

    @Data
    private static class MapVariableTokenHandler implements TokenHandler {
        private Map<String,String> variables;
        private List<String> sqlVariables;

        public MapVariableTokenHandler(Map<String, String> variables) {
            this.variables = variables;
            this.sqlVariables = Lists.newArrayList();
        }

        @Override
        public String handleToken(String content) {
            sqlVariables.add(content);
            if (variables != null && variables.containsKey(content)) {
//                return variables.get(content).toString();
                return "?";
            }
            return "#{" + content + "}";
        }
    }
}
